package org.yscz.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.yscz.common.Constants;
import org.yscz.common.HttpStatus;
import org.yscz.common.Result;
import org.yscz.common.enums.UserResponseEnum;
import org.yscz.entity.Role;
import org.yscz.entity.Testee;
import org.yscz.entity.User;
import org.yscz.entity.vo.UserVo;
import org.yscz.exception.*;
import org.yscz.mqtt.MqttCustomClient;
import org.yscz.service.TesteeService;
import org.yscz.service.UserService;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户接口
 *
 * @author achen
 * @create 2021-08-13 18:45
 */
@RestController
@Slf4j
@Api("用户接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private TesteeService testeeService;

    @Autowired
    private MqttCustomClient mqttCustomClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 登录接口
     *
     * @param user 前台传递的用户数据
     * @return Result对象
     */
    @PostMapping("/user/login")
    @ApiOperation(value = "用户登录接口", httpMethod = "POST")
    public Result login(@RequestBody User user) {
        log.info("user:[{}]", user);

        //登录
        User userDB = userService.login(user);

        Role role = userService.getUserRole(userDB.getUserId());

        JSONObject resultObj = new JSONObject();
        resultObj.put("user", userDB);
        resultObj.put("role", role);

        return Result.success(HttpStatus.SUCCESS, "登陆成功", resultObj);
    }

    /**
     * 新增帐号接口
     *
     * @param userVo 前台传递的用户数据
     * @return Result对象
     */
    @PostMapping("/user/add")
    @ApiOperation(value = "新增帐号接口", httpMethod = "POST")
    public Result add(@RequestBody UserVo userVo) {
        log.info("userVo:[{}]", userVo);
        //notifyAlg(userVo.getUserName());
        //通知算法入人脸库
        //从redis取出imageKey对应的通知算法的信息
        String imageJson = stringRedisTemplate.opsForValue().get(PicturesUploadController.imageKey);
        //JSONObject jsonObject = JSONObject.parseObject(imageJson);
        //通知算法是测评人
        //role：0-测评人 1-被测人
        //jsonObject.put("role", 0);
        //通知算法入人脸库
        mqttCustomClient.publish(Constants.IMAGE_QUALITY_CONTROL_AGAIN, imageJson);
        userService.add(userVo);
        return Result.success(HttpStatus.SUCCESS, "新增帐号成功", "");
    }

    /**
     * 通知算法入人脸库
     */
    public void notifyAlg(String name) {
        //根据用户名去被测人查询
        QueryWrapper<Testee> testeeQueryWrapper = new QueryWrapper<>();
        testeeQueryWrapper.eq("testee_name", name);
        Testee testee = testeeService.getOne(testeeQueryWrapper);

        //根据用户名去账号中查询
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_name", name);
        User user = userService.getOne(userQueryWrapper);

        //从redis取出imageKey对应的通知算法的信息
        String imageJson = stringRedisTemplate.opsForValue().get(PicturesUploadController.imageKey);
        JSONObject jsonObject = JSONObject.parseObject(imageJson);

        //oldRole：0-两个表都没有 1-测评人有，被测人没有 2-被测人有，测评人没有 3-两张表都有
        //newRole：0-测评人 1-被测人
        //如和测评人数据库都没有此条记录
        if (null == testee && null == user) {
            jsonObject.put("oldRole", 0);
        } else if (null == testee && null != user) {
            jsonObject.put("oldRole", 1);
        } else if (null != testee && null == user) {
            jsonObject.put("oldRole", 2);
        } else if (null != testee && null != user) {
            jsonObject.put("oldRole", 3);
        }
        jsonObject.put("newRole", 0);

        //通知算法入人脸库
        mqttCustomClient.publish(Constants.IMAGE_QUALITY_CONTROL_AGAIN, JSONObject.toJSONString(jsonObject));
    }

    /**
     * 修改帐号接口
     *
     * @param userVo 前台传递的用户数据
     * @return Result对象
     */
    @PostMapping("/user/modify")
    @ApiOperation(value = "修改帐号接口", httpMethod = "POST")
    public Result modify(@RequestBody UserVo userVo) {
        log.info("userVo:[{}]", userVo);
        userService.modify(userVo);
        return Result.success(HttpStatus.SUCCESS, "修改帐号成功", "");
    }

    /**
     * 重置密码
     *
     * @param userId 前台传递的用户ID
     * @return Result对象
     */
    @PostMapping("/user/resetPwd/{userId}")
    @ApiOperation(value = "重置密码接口", httpMethod = "POST")
    public Result resetPwd(@PathVariable Long userId) {
        log.info("userId:[{}]", userId);
        userService.resetPwdByUserId(userId);
        return Result.success(HttpStatus.SUCCESS, "重置密码成功", "");
    }

    /**
     * 删除帐号接口
     *
     * @param userId 前台传递的用户ID
     * @return Result对象
     */
    @DeleteMapping("/user/del/{userId}")
    @ApiOperation(value = "删除帐号接口", httpMethod = "DELETE")
    public Result del(@PathVariable Long userId) {
        log.info("userId:[{}]", userId);
        userService.del(userId);
        return Result.success(HttpStatus.SUCCESS, "删除帐号成功", "");
    }

    /**
     * 查询帐号列表接口
     *
     * @param userName 用户名
     * @param phone    帐号
     * @param pageNum  当前页
     * @param pageSize 每页数据条数
     * @return Result对象
     */
    @GetMapping("/user/list")
    @ApiOperation(value = "查询帐号列表接口", httpMethod = "GET")
    public Result list(@RequestParam(value = "userName", required = false) String userName,
                       @RequestParam(value = "phone", required = false) String phone,
                       @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                       @RequestParam(value = "pageSize", required = false, defaultValue = "6") Integer pageSize) {
        JSONObject reusltObj = new JSONObject();
        IPage<User> page = new Page(pageNum, pageSize);
        QueryWrapper queryWrapper = new QueryWrapper();

        if (!StringUtils.isEmpty(userName)) {
            queryWrapper.like("user_name", userName);
        }

        if (!StringUtils.isEmpty(phone)) {
            queryWrapper.like("phone", phone);
        }

        queryWrapper.orderByDesc("update_time");
        IPage<User> userPage = userService.listPage(queryWrapper, page);

        reusltObj.put("list", userPage == null ? new ArrayList<>() : userPage.getRecords());
        reusltObj.put("total", userPage == null ? 0 : userPage.getTotal());

        return Result.success(HttpStatus.SUCCESS, "查询帐号列表成功", reusltObj);
    }

    @GetMapping("/role/list")
    @ApiOperation(value = "查询角色列表接口", httpMethod = "GET")
    public Result roleList() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("role_id");
        List<Role> roles = userService.roleList(queryWrapper);

        return Result.success(HttpStatus.SUCCESS, "查询角色列表成功", roles);
    }

    @GetMapping("/user/detail/{userId}")
    @ApiOperation(value = "查询用户详情接口", httpMethod = "GET")
    public Result getUserDetail(@PathVariable Long userId) {
        UserVo userVo = userService.getUserDetail(userId);
        return Result.success(HttpStatus.SUCCESS, "查询用户详情成功", userVo);
    }
}
